import configparser
from Logger import Logger
from Email import Email

class ConfigController:
    def __init__(self, configFile="./config.ini",logFile="../Logger/logging.json"):
        self.fileurl= configFile
        self.__config = configparser.SafeConfigParser()
        self.__config.read(configFile)
        # self.emailController = Email.EmailController(configPath=configFile)
        self.logger = Logger.Logger(logFile)


    def getConfig(self, sectionName, optionName):
        if self.__config.has_option(sectionName, optionName):
            result = self.__config.get(sectionName, optionName)
            return result
        else:
            return None

    def setConfig(self, sectionName, optionName, value):
        if not self.__config.has_option(sectionName, optionName):
            self.__config.add_section(sectionName)
        self.__config.set(sectionName, optionName, value)

    def saveConfig(self,fileurl):
        fileObj = open(fileurl,'w')
        try:
            self.__config.write(fileObj)
            return True
        except Exception as e:
            self.logger.fileInfoLogger.error("Config controller - Save Error: " , e)
            emailController = Email.EmailController(configPath=self.fileurl)
            emailController.sendEmail(msgStr="保存配置文件时出错，位于ConfigController.py line33。",subject="紧急情况!",withLog=False)
            return False
        finally:
            fileObj.close()

    def removeSection(self,sectionName,fileurl):
        self.__config.remove_section(section=sectionName)
        self.__config.write(open(fileurl,'w'))

if __name__ == '__main__':
    config = ConfigController('./config.ini')
    print(config.getConfig(sectionName="TEST_CONFIG", optionName="TEST_TEXT"))
    config.setConfig(sectionName="TEST_CONFIG",
                     optionName='TEST_TEXT',
                     value='This is test2 !')
    # config.removeSection("TEST_CONFIG",'./config.ini')
    print(config.getConfig(sectionName="TEST_CONFIG", optionName="TEST_TEXT"))
    config.saveConfig('config.ini')
    print(config.getConfig(sectionName="TEST_CONFIG", optionName="TEST_TEXT"))

